/*
 *           佛曰:
 *                   写字楼里写字间，写字间里程序员；
 *                   程序人员写程序，又拿程序换酒钱。
 *                   酒醒只在网上坐，酒醉还来网下眠；
 *                   酒醉酒醒日复日，网上网下年复年。
 *                   但愿老死电脑间，不愿鞠躬老板前；
 *                   奔驰宝马贵者趣，公交自行程序员。
 *                   别人笑我忒疯癫，我笑自己命太贱；
 *                   不见满街漂亮妹，哪个归得程序员？
 *
 * @Descripttion:
 * @version:
 * @Date: 2021-04-20 13:05:47
 * @LastEditors: 墨凡 oncwnuN3VU3V55c1lqO_6llf5DtU@git.weixin.qq.com
 * @LastEditTime: 2021-04-21 12:48:23
 * @Author: huzhushan@126.com
 * @HomePage: https://huzhushan.gitee.io/vue3-element-admin
 * @Github: https://github.com/huzhushan/vue3-element-admin
 * @Donate: https://huzhushan.gitee.io/vue3-element-admin/donate/
 */

/**
 * Parse the time to string
 * @param {(Object|string|number)} time
 * @param {string} cFormat
 * @returns {string | null}
 */
export function parseTime(time, cFormat) {
  if (arguments.length === 0 || !time) {
    return null
  }
  const format = cFormat || '{y}-{m}-{d} {h}:{i}:{s}'
  let date
  if (typeof time === 'object') {
    date = time
  } else {
    if (typeof time === 'string') {
      if (/^[0-9]+$/.test(time)) {
        // support "1548221490638"
        time = parseInt(time)
      } else {
        // support safari
        // https://stackoverflow.com/questions/4310953/invalid-date-in-safari
        time = time.replace(new RegExp(/-/gm), '/')
      }
    }

    if (typeof time === 'number' && time.toString().length === 10) {
      time = time * 1000
    }
    date = new Date(time)
  }
  const formatObj = {
    y: date.getFullYear(),
    m: date.getMonth() + 1,
    d: date.getDate(),
    h: date.getHours(),
    i: date.getMinutes(),
    s: date.getSeconds(),
    a: date.getDay(),
  }
  const time_str = format.replace(/{([ymdhisa])+}/g, (result, key) => {
    const value = formatObj[key]
    // Note: getDay() returns 0 on Sunday
    if (key === 'a') {
      return ['日', '一', '二', '三', '四', '五', '六'][value]
    }
    return value.toString().padStart(2, '0')
  })
  return time_str
}

/**
 * @param {number} time
 * @param {string} option
 * @returns {string}
 */
export function formatTime(time, option) {
  if (('' + time).length === 10) {
    time = parseInt(time) * 1000
  } else {
    time = +time
  }
  const d = new Date(time)
  const now = Date.now()
  const diff = (now - d) / 1000
  if (diff < 30) {
    return '刚刚'
  } else if (diff < 3600) {
    // less 1 hour
    return Math.ceil(diff / 60) + '分钟前'
  } else if (diff < 3600 * 24) {
    return Math.ceil(diff / 3600) + '小时前'
  } else if (diff < 3600 * 24 * 2) {
    return '1天前'
  }
  if (option) {
    return parseTime(time, option)
  } else {
    return (
      d.getMonth() +
      1 +
      '月' +
      d.getDate() +
      '日' +
      d.getHours() +
      '时' +
      d.getMinutes() +
      '分'
    )
  }
}
/**
 * Parse the date to json
 * @param {string} fmt
 * @returns {string | null}
 */
export function timeToJson(fmt) {
  const o = {
    'M+': this.getMonth() + 1, //月份
    'd+': this.getDate(), //日
    'h+': this.getHours(), //小时
    'm+': this.getMinutes(), //分
    's+': this.getSeconds(), //秒
    'q+': Math.floor((this.getMonth() + 3) / 3), //季度
    S: this.getMilliseconds(), //毫秒
  }
  if (/(y+)/.test(fmt)) {
    fmt = fmt.replace(
      RegExp.$1,
      (this.getFullYear() + '').substr(4 - RegExp.$1.length)
    )
  }
  for (var k in o) {
    if (new RegExp('(' + k + ')').test(fmt)) {
      fmt = fmt.replace(
        RegExp.$1,
        RegExp.$1.length == 1 ? o[k] : ('00' + o[k]).substr(('' + o[k]).length)
      )
    }
  }
  return fmt
}
/**
 * 计算两个日期之间的天数
 * @param {string} dateStart 开始日期 yyyy-MM-dd
 * @param {string} dateEnd 结束日期 yyyy-MM-dd
 * @returns {Object} 如果日期相同 返回一天 开始日期大于结束日期，返回0
 */
export function getDaysBetween(dateStart, dateEnd) {
  const startDate = Date.parse(dateStart)
  const endDate = Date.parse(dateEnd)
  return Math.floor((endDate - startDate) / (1 * 24 * 60 * 60 * 1000))
}

/**
 * @param {string} url
 * @returns {Object}
 */
export function getQueryObject(url) {
  url = url == null ? window.location.href : url
  const search = url.substring(url.lastIndexOf('?') + 1)
  const obj = {}
  const reg = /([^?&=]+)=([^?&=]*)/g
  search.replace(reg, (rs, $1, $2) => {
    const name = decodeURIComponent($1)
    let val = decodeURIComponent($2)
    val = String(val)
    obj[name] = val
    return rs
  })
  return obj
}

/**
 * @param {string} input value
 * @returns {number} output value
 */
export function byteLength(str) {
  // returns the byte length of an utf8 string
  let s = str.length
  for (var i = str.length - 1; i >= 0; i--) {
    const code = str.charCodeAt(i)
    if (code > 0x7f && code <= 0x7ff) s++
    else if (code > 0x7ff && code <= 0xffff) s += 2
    if (code >= 0xdc00 && code <= 0xdfff) i--
  }
  return s
}

/**
 * @param {Array} actual
 * @returns {Array}
 */
export function cleanArray(actual) {
  const newArray = []
  for (let i = 0; i < actual.length; i++) {
    if (actual[i]) {
      newArray.push(actual[i])
    }
  }
  return newArray
}

/**
 * @param {Object} json
 * @returns {Array}
 */
export function param(json) {
  if (!json) return ''
  return cleanArray(
    Object.keys(json).map(key => {
      if (json[key] === undefined) return ''
      return encodeURIComponent(key) + '=' + encodeURIComponent(json[key])
    })
  ).join('&')
}

/**
 * @param {string} url
 * @returns {Object}
 */
export function param2Obj(url) {
  const search = decodeURIComponent(url.split('?')[1]).replace(/\+/g, ' ')
  if (!search) {
    return {}
  }
  const obj = {}
  const searchArr = search.split('&')
  searchArr.forEach(v => {
    const index = v.indexOf('=')
    if (index !== -1) {
      const name = v.substring(0, index)
      const val = v.substring(index + 1, v.length)
      obj[name] = val
    }
  })
  return obj
}

/**
 * @param {string} val
 * @returns {string}
 */
export function html2Text(val) {
  const div = document.createElement('div')
  div.innerHTML = val
  return div.textContent || div.innerText
}

/**
 * Merges two objects, giving the last one precedence
 * @param {Object} target
 * @param {(Object|Array)} source
 * @returns {Object}
 */
export function objectMerge(target, source) {
  if (typeof target !== 'object') {
    target = {}
  }
  if (Array.isArray(source)) {
    return source.slice()
  }
  Object.keys(source).forEach(property => {
    const sourceProperty = source[property]
    if (typeof sourceProperty === 'object') {
      target[property] = objectMerge(target[property], sourceProperty)
    } else {
      target[property] = sourceProperty
    }
  })
  return target
}

/**
 * @param {HTMLElement} element
 * @param {string} className
 */
export function toggleClass(element, className) {
  if (!element || !className) {
    return
  }
  let classString = element.className
  const nameIndex = classString.indexOf(className)
  if (nameIndex === -1) {
    classString += '' + className
  } else {
    classString =
      classString.substr(0, nameIndex) +
      classString.substr(nameIndex + className.length)
  }
  element.className = classString
}

/**
 * @param {string} type
 * @returns {Date}
 */
export function getTime(type) {
  if (type === 'start') {
    return new Date().getTime() - 3600 * 1000 * 24 * 90
  } else {
    return new Date(new Date().toDateString())
  }
}

/**
 * @param {Function} func
 * @param {number} wait
 * @param {boolean} immediate
 * @return {*}
 */
export function debounce(func, wait, immediate) {
  let timeout, args, context, timestamp, result

  const later = function () {
    // 据上一次触发时间间隔
    const last = +new Date() - timestamp

    // 上次被包装函数被调用时间间隔 last 小于设定时间间隔 wait
    if (last < wait && last > 0) {
      timeout = setTimeout(later, wait - last)
    } else {
      timeout = null
      // 如果设定为immediate===true，因为开始边界已经调用过了此处无需调用
      if (!immediate) {
        result = func.apply(context, args)
        if (!timeout) context = args = null
      }
    }
  }

  return function (...args) {
    context = this
    timestamp = +new Date()
    const callNow = immediate && !timeout
    // 如果延时不存在，重新设定延时
    if (!timeout) timeout = setTimeout(later, wait)
    if (callNow) {
      result = func.apply(context, args)
      context = args = null
    }

    return result
  }
}

/**
 * This is just a simple version of deep copy
 * Has a lot of edge cases bug
 * If you want to use a perfect deep copy, use lodash's _.cloneDeep
 * @param {Object} source
 * @returns {Object}
 */
export function deepClone(source) {
  if (!source && typeof source !== 'object') {
    throw new Error('error arguments', 'deepClone')
  }
  const targetObj = source.constructor === Array ? [] : {}
  Object.keys(source).forEach(keys => {
    if (source[keys] && typeof source[keys] === 'object') {
      targetObj[keys] = deepClone(source[keys])
    } else {
      targetObj[keys] = source[keys]
    }
  })
  return targetObj
}

/**
 * @param {Array} arr
 * @returns {Array}
 */
export function uniqueArr(arr) {
  return Array.from(new Set(arr))
}

/**
 * @returns {string}
 */
export function createUniqueString() {
  const timestamp = +new Date() + ''
  const randomNum = parseInt((1 + Math.random()) * 65536) + ''
  return (+(randomNum + timestamp)).toString(32)
}

/**
 * Check if an element has a class
 * @param {HTMLElement} elm
 * @param {string} cls
 * @returns {boolean}
 */
export function hasClass(ele, cls) {
  return !!ele.className.match(new RegExp('(\\s|^)' + cls + '(\\s|$)'))
}

/**
 * Add class to element
 * @param {HTMLElement} elm
 * @param {string} cls
 */
export function addClass(ele, cls) {
  if (!hasClass(ele, cls)) ele.className += ' ' + cls
}

/**
 * Remove class from element
 * @param {HTMLElement} elm
 * @param {string} cls
 */
export function removeClass(ele, cls) {
  if (hasClass(ele, cls)) {
    const reg = new RegExp('(\\s|^)' + cls + '(\\s|$)')
    ele.className = ele.className.replace(reg, ' ')
  }
}

/**
 * 保留2位小数，类型不变
 * @param {any} num
 */
export function keepTwoDecimal(num) {
  let result = parseFloat(num)
  if (isNaN(result)) {
    return false
  }
  result = Math.round(num * 100) / 100
  return result
}

// date = new Date()

export function getMW() {
  const date = new Date()
  // console.log(date.toLocaleString())
  const day = date.getDate() //获取当前日期是几号
  // console.log('今天是几号' + day)
  const year = date.getFullYear() // 年份
  var week = date.getDay() // 星期几
  if (week === 0) week = 7
  // console.log('星期几' + week)
  let month = date.getMonth() + 1 // 当前月份
  // console.log('当前月份' + month)
  var curMonthweek = new Date(year, month - 1, 1).getDay(); //当前月1号星期几  
  if (curMonthweek == 0) curMonthweek = 7
  // console.log('当前月1号星期几' + curMonthweek)
  if (curMonthweek == 1) {
    var firstWeekday = (7 - curMonthweek) + 1 //当前月第一周的最后日期
  } else {
    var firstWeekday = (7 - curMonthweek) + 8 //当前月第一周的最后日期 firstWeekday = (7 - curMonthweek) + 8 //当前月第一周的最后日期 
  }
  // console.log('当月第一周最后的日期' + firstWeekday)
  let monthweek = 0
  // console.log(firstWeekday)
  // day < firstWeekday
  // console.log('当前日期 day' + '------' + day)
  // console.log('当前月第一周的最后日期 firstWeekday' + '--------' + firstWeekday)
  if (day <= firstWeekday) {
    // console.log('走这')
    month--
    if (month == 0) {
      month = 12
    }
    // 获取上个月1号 是星期几
    var firstDayLastMonth = new Date(year, month - 1, 1).getDay();
    if (firstDayLastMonth == 0) firstDayLastMonth = 7
    // console.log('获取上个月1号是星期' + firstDayLastMonth)
    // 获取上月的最后一天
    // console.log('上月月份' + month)
    const lastDayThisMonth = new Date(year, month, 0).getDate();
    // console.log('获取上月的最后一天' + lastDayThisMonth)
    if (firstDayLastMonth == 1) {
      var lastsunday = 7 - firstDayLastMonth + 1 //上个月第一周的 周天日期
    } else {
      var lastsunday = 7 - firstDayLastMonth + 8 //上个月第一周的 周天日期
    }
    // console.log('上月第一周的周天日期' + lastsunday)

    if (firstDayLastMonth == 1) {
      if (week == 1) {
        monthweek = Math.floor((lastDayThisMonth) / 7) + 1
      } else {
        monthweek = Math.floor((lastDayThisMonth) / 7)
      }
    } else {
      if (week == 7) {
        monthweek = Math.floor((lastDayThisMonth + day - lastsunday) / 7)
      } else {
        monthweek = Math.floor((lastDayThisMonth + day - lastsunday) / 7) + 1
      }

    }

  } else {
    // console.log('走那')
    month = month
    // var firstDayCurrMonth = new Date(year, month - 1, 1).getDay(); //当前月1号是星期几        
    monthweek = Math.floor((day - week) / 7)
    if (monthweek == 0) monthweek = 1
  }
  let arr = ['', "第一", "第二", "第三", "第四", "第五"]


  // console.log('周数：' + monthweek)
  // console.log('月份：' + month)
  return {
    month: month,
    getWeek: monthweek,
    week: arr[monthweek]
  }
}


export function getStrEndDay(str_week, end_week) {
  // 开始周占月的天数：开始周几(str_week) 距离 结束(周天) 有几天
  let str_num = 0;
  switch (str_week) {
    case 0:
      str_num = 1;
      break;
    case 1:
      str_num = 7;
      break;
    case 2:
      str_num = 6;
      break;
    case 3:
      str_num = 5;
      break;
    case 4:
      str_num = 4;
      break;
    case 5:
      str_num = 3;
      break;
    case 6:
      str_num = 2;
      break;
    case 7:
      str_num = 1;
      break;
  }
  // 末周占月的天数：开始(周天) 距离 结束周几(end_week) 有几天
  let end_num = 0;
  switch (end_week) {
    case 1:
      end_num = 6;
      break;
    case 2:
      end_num = 5;
      break;
    case 3:
      end_num = 4;
      break;
    case 4:
      end_num = 3;
      break;
    case 5:
      end_num = 2;
      break;
    case 6:
      end_num = 1;
      break;
    case 0:
      end_num = 0;
      break;
  }
  return {
    str_num,
    end_num
  };
}

export function getWeekTime(year, month, week) { // 年 月 第几周
  // 获取天数
  var day_num = new Date(year, month, 0).getDate();

  // 该月第一天、最后一天
  const str_day = new Date().setFullYear(year, month - 1, 1);
  const end_day = new Date().setFullYear(year, month, 0);
  //该月第一周、最后一周
  const str_week = new Date(str_day).getDay();
  const end_week = new Date(end_day).getDay();
  const numRes = getStrEndDay(str_week, end_week);
  // console.log(numRes)
  // 该周开始、结束日期 (day)
  let str_time = (week - 1) * 7 + 1;
  let end_time = week * 7;
  if (numRes.str_num != 7) {
    str_time += numRes.str_num;
    end_time += numRes.str_num;
  }
  let mm = Number(month);
  let strDate = year + "." + mm + "." + str_time;
  let endDate = year + "." + mm + "." + end_time;
  if (Number(end_time) > day_num) {
    let mm1 = Number(mm) + 1
    let last_num = Number(end_time) - day_num;
    endDate = year + "." + mm1 + "." + last_num;
  }
  console.log()
  return {
    strDate,
    endDate
  };
}

export function getYMDHMS(timestamp) {
  let time = new Date(timestamp)
  let year = time.getFullYear()
  let month = time.getMonth() + 1
  let date = time.getDate()
  let hours = time.getHours()
  let minute = time.getMinutes()
  let second = time.getSeconds()
  if (month < 10) {
    month = '0' + month
  }
  if (date < 10) {
    date = '0' + date
  }
  if (hours < 10) {
    hours = '0' + hours
  }
  if (minute < 10) {
    minute = '0' + minute
  }
  if (second < 10) {
    second = '0' + second
  }
  const times = year + '-' + month + '-' + date + ' ' + hours + ':' + minute + ':' + second
  return times
}